#!/usr/bin/perl

# photometry script for muniphot and xebm
# miroslav.broz@usa.net, http://www.astrohk.cz, Feb 9th 199

# default values

$name = "V541Cas";
$files = "541cas_*";
$date = "990110";
$cmp = "001";
$df = "dark.fits";
$ff = "flat.fits";
$ap = 4;
$var = 0;
$konve = 1;
$darkbat = 0;
$flatbat = 1;
$muniphot = 1;
$munimatch = 1;
$munilist = 0;
$xebm = 1;

# try to read xebm.config

if (open(id,'<./xebm.config') > 0) {
  $n = 1024;
  read(id,$in,$n);
  close(id);
  @l = split("\n",$in);
# skip comments at the beginning
  $i = 0;
  while (substr($l[$i++],0,1) eq "#") {}
  $i--;

  $name = $l[$i];
  $files = $l[$i+1];
  $date = $l[$i+2];
  $cmp = $l[$i+3];
  $df = $l[$i+4];
  $ff = $l[$i+5];
  $ap = $l[$i+6];
  $var = $l[$i+7];
  $konve = $l[$i+8];
  $darkbat = $l[$i+9];
  $flatbat = $l[$i+10];
  $muniphot = $l[$i+11];
  $munimatch = $l[$i+12];
  $munilist = $l[$i+13];
  $xebm = $l[$i+14];
}

# decide on fits filenames and comparsion SRT file
#  @l = split('\*',$files);
  $fits = $name;
  $cmp = sprintf("%03d",$cmp);
  @lin = (4,7,10,13,16,19,22,25,28,31,34,37,40);	# lines for magnitude data
  @col = (4,5,6,7,8,9,10,11,12,13,14,15,16,17);		# columns for different apertures

# run munipack

if ($konve) {
  print "konve\n";
  qx!ls $files | konve @ mask=$fits???.fits > konve.log!;
#  qx!konve dark.255 mask=dark.fits >> konve.log!;
#  qx!konve flat.255 mask=flat.fits >> konve.log!;
}
if ($darkbat) {
  print "darkbat\n";
  qx!ls $fits*.fits | darkbat @ dark=dark.fits > darkbat.log!
}
if ($flatbat) {
  print "flatbat\n";
  qx!ls $fits*.fits | flatbat @ flat=flat.fits mask=$fits???.fits> flatbat.log!;
}
if ($muniphot) {
  print "muniphot\n";
  qx!ls $fits*.fits | muniphot @ com=com.dat > muniphot.log!;
}
if ($munimatch) {
  print "munimatch\n";
  qx!ls $fits*.SRT | munimatch @ ref="$fits$cmp".SRT > munimatch.log!;
}
if ($munilist) {
  print "munilist\n";

# comparsion stars
#  qx!ls $files.fits | munilist -col=$col[$ap] @ $lin[0] $lin[1] $lin[2] $lin[3] $lin[4] $lin[5] $lin[6] $lin[7] $lin[8] $lin[9] $lin[10] > comparsion.dat!;

# select variable star
  
  if ($var == 0) {
    $var = qx!./apview < "$fits$cmp".SRT!;
  }
  $temp = $lin[0];
  $lin[0] = $lin[$var-1];
  $lin[$var-1] = $temp;
  qx!ls $fits*.fits | munilist -col=$col[$ap] @ $lin[0] $lin[1] $lin[2] $lin[3] $lin[4] $lin[5] $lin[6] $lin[7] $lin[8] $lin[9] $lin[10] > lightcurve.dat!;
}
if ($xebm) {
  print "xebm\n";
  qx!cat $name lightcurve.dat | ./xebm > "$name"_$date.dat!;
}

exit;

